<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>管理员后台 - 学生荣誉信息管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            background: #f6fbff; 
            font-family: 'Segoe UI', Arial, sans-serif; 
            color: #222; 
            line-height: 1.6;
        }
        .header {
            background: #1976d2;
            color: white;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 8px rgba(25,118,210,0.15);
        }
        .header h1 {
            font-size: 24px;
            font-weight: 500;
        }
        .header .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .logout-btn {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .nav-tabs {
            background: white;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            padding: 0 30px;
        }
        .nav-tab {
            padding: 15px 25px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.2s;
            font-weight: 500;
            color: #666;
        }
        .nav-tab.active {
            color: #1976d2;
            border-bottom-color: #1976d2;
            background: #f8f9fa;
        }
        .nav-tab:hover {
            background: #f8f9fa;
        }
        
        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            text-align: center;
            border-left: 4px solid #1976d2;
        }
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            color: #1976d2;
            margin-bottom: 8px;
        }
        .stat-label {
            color: #666;
            font-size: 14px;
        }
        
        .content-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }
        .content-header {
            background: #f8f9fa;
            padding: 20px 30px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .content-header h2 {
            color: #1976d2;
            font-size: 20px;
            font-weight: 500;
        }
        .search-box {
            display: flex;
            gap: 10px;
        }
        .search-box input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            width: 200px;
        }
        .search-box button {
            padding: 8px 16px;
            background: #1976d2;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        .search-box button:hover {
            background: #1565c0;
        }
        
        .table-container {
            overflow-x: auto;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }
        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #1976d2;
            position: sticky;
            top: 0;
        }
        .data-table tr:hover {
            background: #f8f9fa;
        }
        .data-table td {
            font-size: 14px;
        }
        
        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
        }
        .btn-approve {
            background: #4caf50;
            color: white;
        }
        .btn-approve:hover {
            background: #45a049;
        }
        .btn-reject {
            background: #f44336;
            color: white;
        }
        .btn-reject:hover {
            background: #da190b;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        .empty-state h3 {
            margin-bottom: 10px;
            color: #1976d2;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .message {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }
        .message.show {
            transform: translateX(0);
        }
        .message.success {
            background: #4caf50;
        }
        .message.error {
            background: #f44336;
        }
        
        .section {
            display: none;
        }
        .section.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>管理员后台</h1>
        <div class="user-info">
            <span>欢迎，管理员</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="nav-tabs">
        <div class="nav-tab active" onclick="switchTab('students')">学生管理</div>
        <div class="nav-tab" onclick="switchTab('pending-teachers')">待审核教师</div>
        <div class="nav-tab" onclick="switchTab('approved-teachers')">已通过教师</div>
        <div class="nav-tab" onclick="switchTab('rejected-teachers')">审核未通过教师</div>
    </div>

    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number" id="totalStudents">-</div>
                <div class="stat-label">总学生数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="totalTeachers">-</div>
                <div class="stat-label">总教师数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="pendingTeachers">-</div>
                <div class="stat-label">待审核教师</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="approvedTeachers">-</div>
                <div class="stat-label">已通过教师</div>
            </div>
        </div>

        <!-- 学生管理 -->
        <div id="students-section" class="section active">
            <div class="content-section">
                <div class="content-header">
                    <h2>学生列表</h2>
                    <div class="search-box">
                        <input type="text" id="studentSearch" placeholder="搜索学生姓名或学号">
                        <button onclick="searchStudents()">搜索</button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="studentTable">
                        <thead>
                            <tr>
                                <th>学号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>年级</th>
                                <th>班级</th>
                                <th>院系</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>注册时间</th>
                            </tr>
                        </thead>
                        <tbody id="studentTableBody">
                            <tr><td colspan="9" class="loading">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 待审核教师 -->
        <div id="pending-teachers-section" class="section">
            <div class="content-section">
                <div class="content-header">
                    <h2>待审核教师</h2>
                </div>
                <div class="table-container">
                    <table class="data-table" id="pendingTeacherTable">
                        <thead>
                            <tr>
                                <th>工号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>院系</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>注册时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="pendingTeacherTableBody">
                            <tr><td colspan="8" class="loading">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 已通过教师 -->
        <div id="approved-teachers-section" class="section">
            <div class="content-section">
                <div class="content-header">
                    <h2>已通过教师</h2>
                    <div class="search-box">
                        <input type="text" id="teacherSearch" placeholder="搜索教师姓名或工号">
                        <button onclick="searchTeachers()">搜索</button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="approvedTeacherTable">
                        <thead>
                            <tr>
                                <th>工号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>院系</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>审核时间</th>
                                <th>审核人</th>
                            </tr>
                        </thead>
                        <tbody id="approvedTeacherTableBody">
                            <tr><td colspan="8" class="loading">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 审核未通过教师 -->
        <div id="rejected-teachers-section" class="section">
            <div class="content-section">
                <div class="content-header">
                    <h2>审核未通过教师</h2>
                    <div class="search-box">
                        <input type="text" id="rejectedTeacherSearch" placeholder="搜索教师姓名或工号">
                        <button onclick="searchRejectedTeachers()">搜索</button>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table" id="rejectedTeacherTable">
                        <thead>
                            <tr>
                                <th>工号</th>
                                <th>姓名</th>
                                <th>性别</th>
                                <th>院系</th>
                                <th>电话</th>
                                <th>邮箱</th>
                                <th>审核时间</th>
                                <th>审核人</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="rejectedTeacherTableBody">
                            <tr><td colspan="9" class="loading">加载中...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="message" class="message"></div>

    <script>
        let token = '';
        let currentTab = 'students';

        function getToken() {
            return localStorage.getItem('token') || '';
        }

        function showMessage(text, type = 'success') {
            const message = document.getElementById('message');
            message.textContent = text;
            message.className = `message ${type}`;
            message.classList.add('show');
            setTimeout(() => {
                message.classList.remove('show');
            }, 3000);
        }

        function logout() {
            localStorage.removeItem('token');
            window.location.replace('/');
        }

        function switchTab(tabName) {
            // 更新导航栏
            document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));
            event.target.classList.add('active');
            
            // 更新内容区域
            document.querySelectorAll('.section').forEach(section => section.classList.remove('active'));
            document.getElementById(tabName + '-section').classList.add('active');
            
            currentTab = tabName;
            
            // 加载对应数据
            switch(tabName) {
                case 'students':
                    loadStudents();
                    break;
                case 'pending-teachers':
                    loadPendingTeachers();
                    break;
                case 'approved-teachers':
                    loadApprovedTeachers();
                    break;
                case 'rejected-teachers':
                    loadRejectedTeachers();
                    break;
            }
        }

        function loadStats() {
            fetch('/api/admin/teacher-stats', {
                headers: {
                    'Authorization': getToken()
                }
            })
            .then(r => r.json())
            .then(res => {
                if (res.code === 200) {
                    document.getElementById('totalStudents').textContent = res.stats.total_students;
                    document.getElementById('totalTeachers').textContent = res.stats.total;
                    document.getElementById('pendingTeachers').textContent = res.stats.pending;
                    document.getElementById('approvedTeachers').textContent = res.stats.approved;
                }
            })
            .catch(err => {
                console.error('加载统计数据失败:', err);
            });
        }

        function loadStudents() {
            fetch('/api/admin/students', {
                headers: {
                    'Authorization': getToken()
                }
            })
            .then(r => r.json())
            .then(res => {
                if (res.code === 200) {
                    allStudents = res.students; // 存储到全局变量
                    displayStudents(allStudents);
                } else {
                    document.getElementById('studentTableBody').innerHTML = '<tr><td colspan="9" class="empty-state">加载失败</td></tr>';
                }
            })
            .catch(err => {
                console.error('加载学生列表失败:', err);
                document.getElementById('studentTableBody').innerHTML = '<tr><td colspan="9" class="empty-state">网络错误</td></tr>';
            });
        }

        function loadPendingTeachers() {
            fetch('/api/admin/pending-teachers', {
                headers: {
                    'Authorization': getToken()
                }
            })
            .then(r => r.json())
            .then(res => {
                const tbody = document.getElementById('pendingTeacherTableBody');
                if (res.code === 200) {
                    if (res.teachers.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="8" class="empty-state">暂无待审核教师</td></tr>';
                    } else {
                        tbody.innerHTML = res.teachers.map(teacher => `
                            <tr>
                                <td>${teacher.username}</td>
                                <td>${teacher.name}</td>
                                <td>${teacher.gender || '-'}</td>
                                <td>${teacher.department || '-'}</td>
                                <td>${teacher.phone || '-'}</td>
                                <td>${teacher.email || '-'}</td>
                                <td>${teacher.created_at || '-'}</td>
                                <td>
                                    <button class="btn btn-approve" onclick="approveTeacher(${teacher.id}, 'approve')">通过</button>
                                    <button class="btn btn-reject" onclick="approveTeacher(${teacher.id}, 'reject')">拒绝</button>
                                </td>
                            </tr>
                        `).join('');
                    }
                } else {
                    tbody.innerHTML = '<tr><td colspan="8" class="empty-state">加载失败</td></tr>';
                }
            })
            .catch(err => {
                console.error('加载待审核教师列表失败:', err);
                document.getElementById('pendingTeacherTableBody').innerHTML = '<tr><td colspan="8" class="empty-state">网络错误</td></tr>';
            });
        }

        function loadApprovedTeachers() {
            fetch('/api/admin/approved-teachers', {
                headers: {
                    'Authorization': getToken()
                }
            })
            .then(r => r.json())
            .then(res => {
                if (res.code === 200) {
                    allApprovedTeachers = res.teachers; // 存储到全局变量
                    displayApprovedTeachers(allApprovedTeachers);
                } else {
                    document.getElementById('approvedTeacherTableBody').innerHTML = '<tr><td colspan="8" class="empty-state">加载失败</td></tr>';
                }
            })
            .catch(err => {
                console.error('加载已通过教师列表失败:', err);
                document.getElementById('approvedTeacherTableBody').innerHTML = '<tr><td colspan="8" class="empty-state">网络错误</td></tr>';
            });
        }

        function loadRejectedTeachers() {
            fetch('/api/admin/rejected-teachers', {
                headers: {
                    'Authorization': getToken()
                }
            })
            .then(r => r.json())
            .then(res => {
                if (res.code === 200) {
                    allRejectedTeachers = res.teachers; // 存储到全局变量
                    displayRejectedTeachers(allRejectedTeachers);
                } else {
                    document.getElementById('rejectedTeacherTableBody').innerHTML = '<tr><td colspan="9" class="empty-state">加载失败</td></tr>';
                }
            })
            .catch(err => {
                console.error('加载审核未通过教师列表失败:', err);
                document.getElementById('rejectedTeacherTableBody').innerHTML = '<tr><td colspan="9" class="empty-state">网络错误</td></tr>';
            });
        }

        // 全局变量存储原始数据
        let allStudents = [];
        let allApprovedTeachers = [];
        let allRejectedTeachers = [];

        function searchStudents() {
            const searchTerm = document.getElementById('studentSearch').value.trim().toLowerCase();
            const tbody = document.getElementById('studentTableBody');
            
            if (!searchTerm) {
                // 如果搜索框为空，显示所有学生
                displayStudents(allStudents);
                return;
            }
            
            // 筛选匹配的学生
            const filteredStudents = allStudents.filter(student => 
                (student.name && student.name.toLowerCase().includes(searchTerm)) ||
                (student.username && student.username.toLowerCase().includes(searchTerm))
            );
            
            displayStudents(filteredStudents);
        }

        function searchTeachers() {
            const searchTerm = document.getElementById('teacherSearch').value.trim().toLowerCase();
            const tbody = document.getElementById('approvedTeacherTableBody');
            
            if (!searchTerm) {
                // 如果搜索框为空，显示所有已通过教师
                displayApprovedTeachers(allApprovedTeachers);
                return;
            }
            
            // 筛选匹配的教师
            const filteredTeachers = allApprovedTeachers.filter(teacher => 
                (teacher.name && teacher.name.toLowerCase().includes(searchTerm)) ||
                (teacher.username && teacher.username.toLowerCase().includes(searchTerm))
            );
            
            displayApprovedTeachers(filteredTeachers);
        }

        function searchRejectedTeachers() {
            const searchTerm = document.getElementById('rejectedTeacherSearch').value.trim().toLowerCase();
            const tbody = document.getElementById('rejectedTeacherTableBody');
            
            if (!searchTerm) {
                // 如果搜索框为空，显示所有审核未通过教师
                displayRejectedTeachers(allRejectedTeachers);
                return;
            }
            
            // 筛选匹配的教师
            const filteredTeachers = allRejectedTeachers.filter(teacher => 
                (teacher.name && teacher.name.toLowerCase().includes(searchTerm)) ||
                (teacher.username && teacher.username.toLowerCase().includes(searchTerm))
            );
            
            displayRejectedTeachers(filteredTeachers);
        }

        // 显示学生数据的函数
        function displayStudents(students) {
            const tbody = document.getElementById('studentTableBody');
            if (students.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="empty-state">未找到匹配的学生</td></tr>';
            } else {
                tbody.innerHTML = students.map(student => `
                    <tr>
                        <td>${student.username}</td>
                        <td>${student.name}</td>
                        <td>${student.gender || '-'}</td>
                        <td>${student.grade || '-'}</td>
                        <td>${student.class_name || '-'}</td>
                        <td>${student.department || '-'}</td>
                        <td>${student.phone || '-'}</td>
                        <td>${student.email || '-'}</td>
                        <td>${student.created_at || '-'}</td>
                    </tr>
                `).join('');
            }
        }

        // 显示已通过教师数据的函数
        function displayApprovedTeachers(teachers) {
            const tbody = document.getElementById('approvedTeacherTableBody');
            if (teachers.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="empty-state">未找到匹配的教师</td></tr>';
            } else {
                tbody.innerHTML = teachers.map(teacher => `
                    <tr>
                        <td>${teacher.username}</td>
                        <td>${teacher.name}</td>
                        <td>${teacher.gender || '-'}</td>
                        <td>${teacher.department || '-'}</td>
                        <td>${teacher.phone || '-'}</td>
                        <td>${teacher.email || '-'}</td>
                        <td>${teacher.approval_time || '-'}</td>
                        <td>${teacher.approved_by_name || '-'}</td>
                    </tr>
                `).join('');
            }
        }

        // 显示审核未通过教师数据的函数
        function displayRejectedTeachers(teachers) {
            const tbody = document.getElementById('rejectedTeacherTableBody');
            if (teachers.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="empty-state">未找到匹配的教师</td></tr>';
            } else {
                tbody.innerHTML = teachers.map(teacher => `
                    <tr>
                        <td>${teacher.username}</td>
                        <td>${teacher.name}</td>
                        <td>${teacher.gender || '-'}</td>
                        <td>${teacher.department || '-'}</td>
                        <td>${teacher.phone || '-'}</td>
                        <td>${teacher.email || '-'}</td>
                        <td>${teacher.approval_time || '-'}</td>
                        <td>${teacher.approved_by_name || '-'}</td>
                        <td>
                            <button class="btn btn-approve" onclick="approveTeacher(${teacher.id}, 'approve')">重新通过</button>
                        </td>
                    </tr>
                `).join('');
            }
        }

        function approveTeacher(teacherId, action) {
            const actionText = action === 'approve' ? '通过' : '拒绝';
            if (!confirm(`确定要${actionText}该教师的注册申请吗？`)) {
                return;
            }

            fetch(`/api/admin/approve-teacher/${teacherId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': getToken()
                },
                body: JSON.stringify({ action })
            })
            .then(r => r.json())
            .then(res => {
                if (res.code === 200) {
                    showMessage(`审核${actionText}成功`);
                    loadStats();
                    loadPendingTeachers();
                    loadRejectedTeachers();
                } else {
                    showMessage(res.msg || '操作失败', 'error');
                }
            })
            .catch(err => {
                console.error('审核操作失败:', err);
                showMessage('网络错误，请重试', 'error');
            });
        }

        // 页面加载时检查token
        if (!getToken()) {
            window.location.replace('/');
        }

        // 添加搜索框实时搜索功能
        document.addEventListener('DOMContentLoaded', function() {
            // 学生搜索框实时搜索
            const studentSearch = document.getElementById('studentSearch');
            if (studentSearch) {
                studentSearch.addEventListener('input', searchStudents);
            }
            
            // 已通过教师搜索框实时搜索
            const teacherSearch = document.getElementById('teacherSearch');
            if (teacherSearch) {
                teacherSearch.addEventListener('input', searchTeachers);
            }
            
            // 审核未通过教师搜索框实时搜索
            const rejectedTeacherSearch = document.getElementById('rejectedTeacherSearch');
            if (rejectedTeacherSearch) {
                rejectedTeacherSearch.addEventListener('input', searchRejectedTeachers);
            }
        });

        // 加载数据
        loadStats();
        loadStudents();

        // 定期刷新数据
        setInterval(() => {
            loadStats();
            if (currentTab === 'students') loadStudents();
            if (currentTab === 'pending-teachers') loadPendingTeachers();
            if (currentTab === 'approved-teachers') loadApprovedTeachers();
            if (currentTab === 'rejected-teachers') loadRejectedTeachers();
        }, 30000); // 每30秒刷新一次
    </script>
</body>
</html> 